/**各种使用的工具函数
 * 目测会替换掉
 * quick-view.js里面的
 * QuickUrlUtils
 * createOptions
 *
 * quick-easyuiUtils里面的
 * createTreeList
 * */

function QuickUtils(){}

QuickUtils.findByList = function(list, value, valueField){
    var item = null;
    for (var i = 0; i < list.length; i++) {
        var list_item = list[i];
        var v = list_item[valueField];
        if(v == value){
            item = list_item;
        }else{
            var children = list_item["children"];
            if(children && children.length>0){
                item = QuickUtils.findByList(children, value, valueField);
                if(!item){
                    continue;
                }else{
                    break;
                }
            }
        }
    }
    return item;
}

QuickUtils.createTreeList = function(config){
    var finalConfig = $.extend({}, QuickUtils.convertTreeListDefaultConfig, config);
    var list = finalConfig["list"];
    var sjdm = finalConfig["sjdm"];
    var idField = finalConfig["idField"];
    var textField = finalConfig["textField"];
    var reldateField = finalConfig["reldateField"];
    var itemIDField = finalConfig["itemIDField"];
    var itemTextField = finalConfig["itemTextField"];
    return QuickUtils.innerCreateTreeList(list, sjdm, idField, textField, reldateField, itemIDField, itemTextField);
}

QuickUtils.innerCreateTreeList = function(list, sjjgdm, idField, textField, reldateField, itemIDField, itemTextField){
    var childList = [];
    for (var i = 0; i < list.length; i++) {
        var item = list[i];
        if (item == null) {
            continue;
        }
        var sjjgdm1 = item[reldateField];
        if (sjjgdm1 != sjjgdm) {
            continue;
        } else {
            var id = item[idField];
            item[itemTextField] = item[textField];
            item[itemIDField] = item[idField];
            var lt = QuickUtils.innerCreateTreeList(list, id, idField, textField, reldateField, itemIDField, itemTextField);
            if (lt != null && lt.length != 0)
            {
                item["children"] = lt;
            }
            childList.push(item);
            list[i] = null;
        }
    }
    if (childList.length == 0) {
        childList = null;
    }
    return childList;
}

QuickUtils.convertTreeListDefaultConfig = {
    /*上级代码值*/
    sjdm: ""
    /*ID字段*/
    ,idField: "XMDM"
    /*text字段*/
    ,textField: "XMMC"
    /*关联字段*/
    ,reldateField: "SJDM"
    /*item的id字段*/
    ,itemIDField: "id"
    /*item的text字段*/
    ,itemIDField: "text"
};

/**URL工具类*/
(function ($) {
    var host = window.location.host;
    var pathName = window.document.location.pathname.replace(/\/\//g, "/");
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/')+1);
    var currPagePath = pathName.substring(0, pathName.substr(1).lastIndexOf('/')+1)
    $.QuickUrlUtils = {
        redirectUrl: function(url)
        {
            location = currPagePath + "/" + url;
        },
        redirectRootUrl: function(url)
        {
            location = projectName + "/" + url;
        }
        ,getProjectName: function(){

            return projectName;
        }
        ,geCurrPagePath: function()
        {
            return currPagePath;
        }
        ,getHost: function(){
            return host;
        }
        ,getHostProject: function(){
            return host + projectName;
        }
        ,forward: function(url, title, subTitle,isClose)
        {
            StoreCache.setCache("title",title);
            if($.QuickVersion["isWeb"])
            {
                location = url;
            }
            else if($.QuickVersion["isWeixin"])
            {
                location = url;
            }
            else if($.QuickVersion["android"])
            {
                if(!isClose) isClose = "2";
                var tzurl =currPagePath+"/"+url;
                if(url.indexOf("FJZLYD")!=-1){
                    tzurl = url;
                }
                android.toWebViewActivity(tzurl, title, "",isClose);
            }
            else if($.QuickVersion["iPhone"])
            {
                window.webkit.messageHandlers.fjzlyd.postMessage({functionName:"toWebViewActivity",parameter:{url: currPagePath+"/"+url, title: title, subTitle: "", isClose: isClose }});
            }
        }
        ,forwardRootUrl: function(url, title, subTitle,isClose)
        {
            if($.QuickVersion["isWeb"])
            {
                location = projectName+"/"+url;
            }
            else if($.QuickVersion["isWeixin"])
            {
                location = projectName+"/"+url;
            }
            else if($.QuickVersion["android"])
            {
                if(!isClose) isClose = "2";
                android.closeAllWebView(projectName+"/"+url, title, "",isClose);
            }
            else if($.QuickVersion["iPhone"])
            {
                window.webkit.messageHandlers.fjzlyd.postMessage({functionName:"toWebViewActivity",parameter:{url: projectName+"/"+url, title: title, subTitle: "", isClose: isClose }});
            }
        }
        ,forwardAny: function(url)
        {
            location = url;
        }
        ,openNewWindow: function(url, title)
        {
            window.open(url);
        }
        //获取URL参数
        ,getRequest: function(key) {
            var url = decodeURI(location.search); //获取url中"?"符后的字串
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substring(url.indexOf("?")+1, url.length);
                strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    if(!StringUtils.isEmpty(strs[i]))
                        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                }
            }
            if (!key)
                return theRequest;
            else
                return theRequest[key];
            // var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            // var r = window.location.search.substr(1).match(reg);  //匹配目标参数
            // if (r != null) return unescape(r[2]); return null; //返回参数值
        }
        //获取URL参数
        ,getRequestByURL: function(url, key) {
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substring(url.indexOf("?")+1, url.length);
                strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                }
            }
            if (key == "")
                return theRequest;
            else
                return theRequest[key];
        }
        /**退回上级页面*/
        ,back: function(){
            history.back(-1);
        }
        /**预留jsbriage统一页面跳转*/
        ,redirectJSBridge: function(options,data){
            // if($.QuickVersion["isIOSApp"] || $.QuickVersion["isApp"]){
            //     //console.log('use app');
            //     var params = {
            //         "type": "H5",
            //         "toPage": options["url"],
            //         "hasNavigation": "true",
            //         "animate":options.animate==undefined?"push":options.animate,
            //         "params":data!=undefined?data:{},
            //         "refreshUrl":options["refreshUrl"]
            //     };
               

            //     JSBridge.prototype.callHandler("forward", params);

            //     //JSBridge.prototype.callHandler("gotoWebView", options);
            // }
            // else if($.QuickVersion["isWeixin"] ||$.QuickVersion["isWeb"])
            // {
                location.href = options["url"];
                //当出现登录超时时，记住当前地址，登录之后跳转到当前地址。登录页和注册页以及忘记密码页 不做登录之后跳转的地址保存
                if(options && options["url"] && options["url"].indexOf('login')<0){
                     StoreCache.setCache("afterLoginUrl",location.href);
                }else{
                     StoreCache.removeCache("afterLoginUrl");
                }
            // }
            // else
            // {

            // }
        }
        /**预留jsbriage统一页面返回*/
        ,rebackJSBridge: function(options){
            // if($.QuickVersion["isWeixin"]){
            //     location = options["url"];
            // }
            // else if($.QuickVersion["isIOSApp"] || $.QuickVersion["isApp"]){
                // if(StringUtils.isEmpty(options["app_user_agent"])){
                //     options["url"] =  currPagePath + "/" + options["url"];
                // }
                // var params = {
                //     "type": "H5",
                //     "toPage": options["url"],
                //     "hasNavigation": "true",
                //     "animate":"pop",
                // };

                // JSBridge.prototype.callHandler("forward", params);

                //JSBridge.prototype.callHandler("backtoWebView", options);
            // }
            // else if($.QuickVersion["isWeb"])
            // {
                location = options["url"];
            // }
            // else
            // {

            // }
        }
        /**预留jsbriage统一页面刷新*/
        ,refreshJSBridge: function(options){
            // if($.QuickVersion["isIOSApp"] || $.QuickVersion["isApp"]){
            //     JSBridge.prototype.callHandler("refreshPage", options);
            // }
            // else if($.QuickVersion["isWeb"] && options["url"])
            // {
                location = options["url"];
            // }
            // else
            // {
            // }
        }
        //在不提供上一页地址，返回上一页并刷新
        ,reBackAndRefreshJSBridge: function(url,topage){
            // if($.QuickVersion["isIOSApp"] || $.QuickVersion["isApp"]){
            //     var options = {
            //         "type": "H5",
            //         "toPage": topage?topage:"",
            //         "hasNavigation": "true",
            //         "animate":"pop",
            //         "refreshUrl":url?url:""
            //     };
            //     JSBridge.prototype.callHandler("forward", options);
            // }
            // else
            // {
                history.back(-1)
            // }
        }
    }
})(jQuery);

/**创建下拉框选项*/
(function($) {
    var defaultConfig = {
        needNull: "true"
        ,textField: "XMMC"
        ,valueField: "XMDM"
    };
    $.fn.createOptions = function(ary, config)
    {
        var finalConfig = $.extend({}, defaultConfig, config);
        $(this).empty();
        var needNull = finalConfig["needNull"];
        var textField = finalConfig["textField"];
        var valueField = finalConfig["valueField"];

        var opts = [];

        if(needNull == "true")
        {
            var opt = $('<option>');
            opt.attr("value", "");
            opt.text("请选择");
            //opt.css("display", "none");
            opts.push(opt);
        }
        for(var i=0; i<ary.length; i++)
        {
            var item = ary[i];
            var value = item[valueField];
            var text = item[textField];
            var option = $('<option>');
            $(option).attr('value', value);
            $(option).html(text);
            $(option).data(item);
            var children = item['children'];
            if(!StringUtils.isEmpty(children))
            {
                $(option).attr("children", JSON.stringify(children));
            }
            opts.push(option);
            //options += $(option)[0].outerHTML;
        }
        $(this).append(opts);
    };

})(jQuery);
/**与原生交互*/
(function($) {
$.JkcsUtils = {
        getUserLocation: function(callback, params){
            if($.QuickVersion["isWeb"])
            {
                jwd = "115.894666,28.694741";
                params["userLocation"] = jwd;
                if(callback)
                    callback(params);
            }
            else
            {
                alert("开始获取location")
                JSBridge.prototype.callHandler("nativePermission",  params);
                JSBridge.prototype.callHandler("nativePermission",  {
                    "type": "location",
                    "callBackMethod": callBack,
                    "params": params
                });
                // JSBridge.prototype.getJwd(callback, params);
            }
        },
        /**跳转到首页的方法*/
        gotoHome: function(options){
            if($.QuickVersion["isWeb"]) {
                location =  options["url"];
            }else{
                // alert(JSON.stringify(options));
                JSBridge.prototype.callHandler("gotoHome", options);
            }
        },
        /**收藏按钮图片加载*/
        loadScImg: function(sfsc){
            if($.QuickVersion["isWeb"])
            {
                if(sfsc == 0){
                    $(".sc-icon").removeAttr("style");
                }else{
                    $(".sc-icon").attr("style","background:url('/static/images/red-star.png') no-repeat;background-size: 100% 100%;");
                }
            }
            else
            {
                var params = {
                    "title" : title
                };
                if(sfsc == "1"){
                    params["scImg"] = "sc_red";
                }else{
                    params["scImg"] = "sc_white";
                }

                var option = $.JkcsTile.getTitle(titleType,params);

                $.JkcsUtils.setHeader(option);

                //JSBridge.prototype.callHandler("loadScImg",  {sfsc: sfsc});
            }
        },
        /**jsbridge注册*/
        jsbridgeRegister: function(funName, initFunction, params){
            if($.QuickVersion["isApp"] || $.QuickVersion["isIOSApp"] )
            {
                JSBridge.prototype.registerHandler(funName, initFunction, params);
            }
        },
        /**调用原生地图*/
        gotoMap: function(params){
            if($.QuickVersion["isApp"] || $.QuickVersion["isIOSApp"] )
            {
                JSBridge.prototype.callHandler("forward",  {
                    "type": "Native",
                    "toPage": "gotoMap",
                    "hasNavigation": "false",
                    "params": params
                });
            }
        },
        /**设置头部*/
        setHeader: function(params){
            // alert("进入setHeader");
            if($.QuickVersion["isIOSApp"] )
            {
                // alert("进入app的判断");
                JSBridge.prototype.callHandler("setHeader",  params);
            } else if ($.QuickVersion["isApp"]) {
                if (window.WebViewJavascriptBridge) {
                    //do your work here
                    // appInit();
                    JSBridge.prototype.callHandler("setHeader",  params);
                } else {
                    document.addEventListener(
                        'WebViewJavascriptBridgeReady'
                        , function() {
                            // appInit();
                            JSBridge.prototype.callHandler("setHeader",  params);
                            //do your work here
                        },
                        false
                    );
                }
            }
        },
        /**请求数据*/
        requestData: function(params){
            if($.QuickVersion["isApp"] || $.QuickVersion["isIOSApp"] )
            {
                JSBridge.prototype.callHandler("requestData",  params);
            }
        },
        /**请求数据*/
        forward: function(params){
            if($.QuickVersion["isApp"] || $.QuickVersion["isIOSApp"] )
            {
                JSBridge.prototype.callHandler("forward",  params);
            }
        },
        /**原生权限*/
        nativePermission: function(params){
            if($.QuickVersion["isApp"] || $.QuickVersion["isIOSApp"] )
            {
                JSBridge.prototype.callHandler("nativePermission",  params);
            }
        }
    }
})(jQuery);